package cn.jtfadmin.base.lang.common.utils;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 唯一键生成工具
 *
 * @author jtf
 * @since 0.0.1
 */
public class IdGenUtils {

    /**
     * 16进制char
     */
    private static final char[] HEX_CHARS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * uuid 生成方式<br/>
     * UUID.randomUUID().toString().replaceAll("\\-", "")
     *
     * @return uuid
     */
    public static String uuidGen() {
        return UUID.randomUUID().toString().replaceAll("\\-", "");
    }


    /**
     * 通过MD5生成32位唯一数字
     *
     * @return 通过MD5生成32位唯一数字
     */
    public static String md5Gen() {

        try {
            return new String(
                    encodeHex(
                            MessageDigest.getInstance("MD5")
                                    .digest(uuidGen().getBytes(StandardCharsets.UTF_8))
                    )
            );
        } catch (NoSuchAlgorithmException ex) {
            // jdk已内置，不会发生
            throw new IllegalStateException("Could not find MessageDigest with algorithm MD5", ex);
        }
    }

    private static char[] encodeHex(byte[] bytes) {
        char[] chars = new char[32];
        for (int i = 0; i < chars.length; i = i + 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
            chars[i + 1] = HEX_CHARS[b & 0xf];
        }
        return chars;
    }
}
